// React hooks for data management
import { useEffect } from 'react';
import { useAgentStore } from '../stores/useAgentStore';
import { useMcpStore } from '../stores/useMcpStore';
import { useChatStore } from '../stores/useChatStore';
import apiService from './api';
import type { McpService } from '../components/ToolManager';
import type { Agent } from '../components/AgentManager';

// Agent management hook - 使用新的 store
export function useAgents() {
  const { agents, setAgents, addAgent, removeAgent } = useAgentStore();

  const loadAgents = async () => {
    try {
      const data = await apiService.getAgents();
      setAgents(data);
    } catch (err) {
      console.error('Failed to load agents:', err);
    }
  };

  const createAgent = async (agent: Partial<Agent>) => {
    try {
      const newAgent = await apiService.createAgent(agent);
      addAgent(newAgent);
      return newAgent;
    } catch (err) {
      console.error('Failed to create agent:', err);
      throw err;
    }
  };

  const deleteAgent = async (id: string) => {
    try {
      await apiService.deleteAgent(id);
      removeAgent(id);
    } catch (err) {
      console.error('Failed to delete agent:', err);
      throw err;
    }
  };

  useEffect(() => {
    loadAgents();
  }, []);

  return {
    agents,
    createAgent,
    deleteAgent,
    refresh: loadAgents,
  };
}

// MCP service management hook - 使用新的 store
export function useMcpServices() {
  const { mcpServices, mcpTools, setMcpServices, addMcpService, removeMcpService, setMcpTools } = useMcpStore();

  const loadServices = async () => {
    try {
      const data = await apiService.getMcpServices();
      console.log("getMcpServices:", data);
      setMcpServices(data);
    } catch (err) {
      console.info('Failed to load services:', err);
    }
  };

  const loadTools = async () => {
    try {
      const data = await apiService.getMcpTools();
      console.log("getMcpTools:", data);
      if (data.tools) {
        setMcpTools(data.tools);
      }
    } catch (err) {
      console.info('Failed to load tools:', err);
    }
  };

  const createService = async (service: Partial<McpService>) => {
    try {
      const newService = await apiService.createMcpService(service);
      addMcpService(newService);
      return newService;
    } catch (err) {
      console.error('Failed to create service:', err);
      throw err;
    }
  };

  const deleteService = async (id: string) => {
    try {
      await apiService.deleteMcpService(id);
      removeMcpService(id);
    } catch (err) {
      console.error('Failed to delete service:', err);
      throw err;
    }
  };

  const executeTool = async (toolName: string, args: Record<string, any>) => {
    try {
      const result = await apiService.executeMcpTool(toolName, args);
      return result;
    } catch (err) {
      console.error('Failed to execute tool:', err);
      throw err;
    }
  };

  const refreshAll = async () => {
    await Promise.all([loadServices(), loadTools()]);
  };

  useEffect(() => {
    refreshAll();
  }, []);

  return {
    services: mcpServices,
    tools: mcpTools,
    createService,
    deleteService,
    executeTool,
    refreshServices: loadServices,
    refreshTools: loadTools,
    refreshAll,
  };
}

// Chat hook - 使用新的 store
export function useChat() {
  const {
    chatMessages: messages,
    isLoading: loading,
    setChatMessages: setMessages,
    addChatMessage,
    setLoading
  } = useChatStore();

  const sendMessage = async (message: string, agentName?: string, history?: Array<{ role: string; content: string }>) => {
    setLoading(true);

    try {
      // 如果没有指定 agentName，使用默认值
      const agent = agentName || "default";

      const response = await apiService.chat(agent, {
        prompt: message,
        history: history || messages.slice(-10),
      });

      const assistantMessage = {
        id: `assistant-${Date.now()}`,
        role: "assistant" as const,
        content: response.message || response.content,
        timestamp: new Date()
      };

      addChatMessage(assistantMessage);
      return assistantMessage;
    } catch (err) {
      console.error('Failed to send message:', err);
      throw err;
    } finally {
      setLoading(false);
    }
  };

  const clearMessages = () => {
    setMessages([]);
  };

  return {
    messages,
    loading,
    sendMessage,
    clearMessages,
  };
}

// Stream chat hook
export function useStreamChat() {
  const { setLoading } = useChatStore();

  const streamMessage = async (
    message: string,
    agentId?: string,
    history?: Array<{ role: string; content: string }>,
    onChunk?: (chunk: string) => void,
    onComplete?: (fullMessage: string) => void
  ) => {
    setLoading(true);

    try {
      const response = await apiService.streamChat({
        agent_id: agentId,
        prompt: message,
        history: history || [],
      });

      const reader = response.body?.getReader();
      const decoder = new TextDecoder();
      let fullMessage = '';

      if (reader) {
        while (true) {
          const { done, value } = await reader.read();
          if (done) break;

          const chunk = decoder.decode(value);
          fullMessage += chunk;
          onChunk?.(chunk);
        }
      }

      onComplete?.(fullMessage);
      return fullMessage;
    } catch (err) {
      console.error('Failed to stream message:', err);
      throw err;
    } finally {
      setLoading(false);
    }
  };

  return {
    streamMessage,
  };
}
